using System;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
using System.Collections;

public class TcpImageUploaderUtil
{
    private string serverIP = "47.109.66.207";
    private int serverPort = 19999;
    private TcpClient client;
    private NetworkStream stream;

    public bool IsConnected => client != null && client.Connected;

    // 连接服务器
    public bool Connect(string ip="", int port=0)
    {
        try
        {
            if (!string.IsNullOrEmpty(ip) && port != 0)
            {
                serverIP = ip;
                serverPort = port;
            }

            client = new TcpClient();
            client.Connect(serverIP, serverPort);
            stream = client.GetStream();
            Debug.Log($"已连接服务器 {serverIP}:{serverPort}");
            return true;
        }
        catch (Exception e)
        {
            Debug.LogError("连接服务器失败: " + e.Message);
            return false;
        }
    }

    // 上传图片协程（纯协程版）
    public IEnumerator SendImageCoroutine(Texture2D image, Action<string> onResult)
    {
        //发送文件使用TCP，格式:"Image@" + base64Str + "[&&]";
        //收到的url拼接之后: "http://47.109.66.207:8080/Images/2025_10_29/09_42_59.jpg";
        
        if (!IsConnected && !Connect())
            yield break;

        byte[] imgBytes = image.EncodeToJPG();
        string base64Str = Convert.ToBase64String(imgBytes);
        string message = "Image@" + base64Str + "[&&]";
        byte[] data = Encoding.UTF8.GetBytes(message);

        // 发送数据（分块，避免阻塞）
        int chunkSize = 1024 * 16; // 16KB 每块
        for (int offset = 0; offset < data.Length; offset += chunkSize)
        {
            int len = Math.Min(chunkSize, data.Length - offset);
            stream.Write(data, offset, len);
            yield return null; // 切回主线程
        }
        Debug.Log($"图片已发送，大小 {data.Length} 字节");

        // 接收服务器返回
        byte[] buffer = new byte[4096];
        StringBuilder replyBuilder = new StringBuilder();
        float timeout = 5f;
        float timer = 0f;

        while (timer < timeout)
        {
            if (stream.DataAvailable)
            {
                int read = stream.Read(buffer, 0, buffer.Length);
                if (read > 0)
                {
                    string chunk = Encoding.UTF8.GetString(buffer, 0, read);
                    replyBuilder.Append(chunk);
                    Debug.Log($"收到数据: {chunk}");
                }
                else
                {
                    Debug.Log("服务器连接已关闭");
                    break;
                }
            }
            else
            {
                yield return null;
                timer += Time.deltaTime;
            }
        }

        string reply = replyBuilder.ToString().Trim();
        Debug.Log($"服务器完整返回: {reply}");
       
        if (!string.IsNullOrEmpty(reply))
        {
            string url = $"http://{serverIP}:8080/Images/{reply}";
            Debug.Log($" 图片访问地址: {url}");
            onResult?.Invoke(url);
        }
        else
        {
            Debug.LogWarning("未能识别服务器返回的图片地址");
            onResult?.Invoke("");
        }
    }


    public void Close()
    {
        if (stream != null) stream.Close();
        if (client != null) client.Close();
    }
}
